package com.LLL.product;

import com.LLL.DBUtill;
import com.LLL.customer.model.Product;
import com.google.gson.Gson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

@WebServlet("/product_list.do")
public class ProductListServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {
        //1、获取连接
        Connection conn = DBUtill.getConnection();
        //2、准备SQL
        String sql = "select * from tb_product order by create_time desc limit 10";
        //声明操作对象和结果集集对象
        PreparedStatement ps = null;
        ResultSet rs = null;
        //4、获取操作对象
        try {
            ps = conn.prepareStatement(sql);
            //5、执行SQL获取结果集
            rs = ps.executeQuery();
            //6、解析对象
            ArrayList list = new ArrayList();
            while (rs.next()) {
                //7、创建对象并设置数据
                Product product = new Product();
                product.setId(rs.getInt("id"));
                product.setCategory_main_id(rs.getString("category_main_id"));
                product.setCategory_branch_id(rs.getString("category_branch_id"));
                product.setName(rs.getString("name"));
                product.setProducing_area(rs.getString("producing_area"));
                product.setDescription(rs.getString("description"));
                product.setCreate_time(rs.getString("create_time"));
                product.setMarket_price(rs.getDouble("market_price"));
                product.setSell_price(rs.getDouble("sell_price"));
                product.setProduct_amount(rs.getInt("product_amount"));
                product.setPicture(rs.getString("picture"));
                product.setDiscount(rs.getString("discount"));
                //8、将商品信息添加到list中
                list.add(product);
                //9、将对象置为空，让GC尽快回收内存
                product = null;
            }
            //9、返回数据
            resp.setContentType("application/json; charset=utf-8");
            //需要添加依赖
            Gson gson = new Gson();
            //将list对象转为JSON格式字符串
            String result = gson.toJson(list);
            //输出转换后的字符串数据
            resp.getWriter().println(result);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        DBUtill.clossResource(conn, ps, rs);
//        req.getRequestDispatcher("product_list.jsp").forward(req, resp);
    }
}
